<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>getSnapshotBeforeUpdate</title>
    <style>
        .news {
            height: 30px;
            width: 300px;
        }

        .list {
            height: 150px;
            overflow: auto;
            background-color: aquamarine;
        }
    </style>
</head>

<body>
    <div id="test"></div>
    <script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
    <script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
    <script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>
    <script type="text/babel">
        //1 创建类式组件
        class NewsList extends React.Component {

            state = {
                newsArr: []
            }
            //在这个钩子中做一 些初始化的事，例如:开后定时器、发送网络请求、订阅消息
            componentDidMount() {
                setInterval(() => {
                    //获取原状态
                    const { newsArr } = this.state
                    //模拟一条新闻
                    const news = '新闻' + (newsArr.length + 1)
                    //更新状态
                    this.setState({ newsArr: [news, ...newsArr] })
                }, 1000)

            }
            render() {
                console.log("Count--render")
                return (
                    <div className='list' ref="list">
                        {this.state.newsArr.map((news, index) => {
                            return <div key={index} className="news">{news}</div>
                        })}
                    </div>
                )
            }
            getSnapshotBeforeUpdate() {
                //scrollHeight  list 的高度（上次）
                return this.refs.list.scrollHeight
            }
            componentDidUpdate(preProps, preState, shapshotValue) {
                //scrollTop 滚动条距离顶部的的高度
                this.refs.list.scrollTop += this.refs.list.scrollHeight - shapshotValue
            }
        }
        //2 渲染组件到页面 
        ReactDOM.render(<NewsList />, document.getElementById('test'))

    </script>
</body>

</html>